<script setup lang="ts">
import { onMounted, reactive } from "vue";
import type { MenuOption } from 'naive-ui';
import {
  useMessage,
  NMenu,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NCarousel
} from "naive-ui";
import statusCode from "../api/statusCode";
import { Category, getCategories } from "../api/category";
import router from "../router";
import { getSlider, Slider } from "../api/statistics";

const message = useMessage();

const queryCategories = async () => {
  try {
    const resp = await getCategories();
  
    if (resp.status === statusCode.SUCCESS) {
      return resp.data;
    } else {
      throw new Error(`错误码 ${resp.status}`);
    }
  } catch (error) {
    message.error("" + error);
    return [];
  }
};

const querySlider = async () => {
  try {
    const resp = await getSlider();
  
    if (resp.status === statusCode.SUCCESS) {
      return resp.data;
    } else {
      throw new Error(`错误码 ${resp.status}`);
    }
  } catch (error) {
    message.error("" + error);
    return [];
  }
};

const convertCategoryToOption = (category: Category) => {
  const o: MenuOption = { label: category.categoryName, key: category.categoryId };
  if (category.list) o.children = category.list.map(child => convertCategoryToOption(child));
  return o;
};

const options = reactive<MenuOption[]>([]);

const createMenu = async () => {
  const categories = await queryCategories();

  options.length = 0;
  options.push(...categories.map(convertCategoryToOption));
};

const sliders = reactive<Slider[]>([]);
const createSlider = async () => {
  const sliderInfos = await querySlider();

  sliders.length = 0;
  sliders.push(...sliderInfos);
};

onMounted(() => {
  createMenu();
  createSlider();
});

const handleUpdateValue = (_key: string, item: MenuOption) => {
  const label = item.label;
  if (typeof label == 'string') router.push({ name: 'search', query: { q: label.trim() }});
};
</script>
<template>
  <p>首页</p>
  <n-layout has-sider>
    <n-layout-sider>
      <n-menu
        @update:value="handleUpdateValue"
        :options="options"
        :default-expanded-keys="[] /* we leave this empty because we don't want it to expand on default.*/"
        accordion
      />
    </n-layout-sider>
    <n-layout-content
      content-style="padding: 0 12px;"
    >
      <n-carousel
        autoplay
      >
        <router-link
          class="block"
          v-for="info of sliders"
          :key="info.productId"
          :to="{ name: 'product', params: { storeId: info.storeId, productId: info.productId } }"
        >
          <img
            class="carousel-img"
            :src="info.img"
          >
        </router-link>
      </n-carousel>
    </n-layout-content>
  </n-layout>
</template>

<style scoped>
.block {
  display: block;
}
.carousel-img {
  width: 100%;
  height: 500px;
  object-fit: cover;
}
</style>
